package com.jiangnan.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiangnan.entity.Book
import com.jiangnan.repository.BookRepository
import com.jiangnan.util.EventUtil
import kotlinx.coroutines.launch
import okhttp3.MultipartBody

class ISBNViewModel : ViewModel() {
    private val TAG = "ISBNViewModel"

    // 扫描结果（ISBN）
    private val _book = MutableLiveData<Book?>()
    val book: LiveData<Book?> = _book

    private val _toastMessage  = MutableLiveData<EventUtil<String>>()
    val toastMessage : LiveData<EventUtil<String>> = _toastMessage

    private val repository = BookRepository()

    // 新增封面 URL LiveData
    private val _coverUrl = MutableLiveData<String>()
    val coverUrl: LiveData<String> get() = _coverUrl

    // 你的 API Key（请替换成真实的 key）
    private val apiKey = "ba9c60752ca78cb6de2c4c9cfedfe0b5"

    fun setScanResult(result: String) {
        fetchBookInfo(result)
    }

    private fun fetchBookInfo(isbn: String) {
        // 更新提示文本
        viewModelScope.launch {
            try {
                // 调用仓库函数，传入 API Key 和 ISBN 获取 Response<Book>
                val response = repository.fetchBook(apiKey, isbn)
                if (response.code == 1) {
                    val book = response.data
                    _book.postValue(book)
                    _toastMessage.postValue(EventUtil("获取图书信息成功"))
                } else {
                    _book.postValue(null)
                    _toastMessage.postValue(EventUtil("获取图书信息失败，请检查网络"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("已取消扫描"))
            }
        }
    }

    fun saveBook(book: Book){
        try {
            viewModelScope.launch {
                book.lastNum = book.sum
                val response = repository.saveBook(book)
                if (response.code == 1) {
                    _toastMessage.postValue(EventUtil("保存成功"))
                } else {
                    _toastMessage.postValue(EventUtil("保存失败，请检查网络"))
                }
            }
        } catch (e: Exception) {
            _toastMessage.postValue(EventUtil("添加书籍报错了"))
            e.printStackTrace()
        }
    }

    /**
     * 上传图片的方法
     */
    fun uploadCoverImage(filePart: MultipartBody.Part) {
        viewModelScope.launch {
            try {
                val response = repository.uploadImage(filePart)
                if (response.isSuccessful) {
                    response.body()?.let { res ->
                        if (res.code == 1) {  // 假设 code==1 表示成功
                            _book.value?.let { book ->
                                book.img = res.data ?: ""
                            }
                            _coverUrl.postValue(res.data ?: "")
                            _toastMessage.postValue(EventUtil("上传成功"))
                        } else {
                            _toastMessage.postValue(EventUtil("上传失败：${res.msg}"))
                        }
                    }
                } else {
                    _toastMessage.postValue(EventUtil("上传失败：HTTP ${response.code()}"))
                }
            } catch (e: Exception) {
                e.printStackTrace()
                _toastMessage.postValue(EventUtil("上传异常：${e.message}"))
            }
        }
    }

    /**
     * 上传后清空页面
     */
    fun clear(){
        val clearBook = Book(
            id = null,
            title = "",
            img = "",
            author = "",
            isbn = "",
            publisher = "",
            pubdate = "",
            pubplace = "",
            pages = "",
            price = "",
            binding = "",
            edition = "",
            format = "",
            summary = "",
            lastNum = "",
            sum = "",
            recommendNum = "",
            createTime = "",
            updateTime = "",
            operateDate = ""
        )
        _book.postValue(clearBook)
    }

}